import time

from cjc.tools.logger import Logger


class DetectorScheduler:
    """分流器，为了提高程序效率实行轮流检测"""

    def __init__(self, step=1):
        """每隔step秒执行一次   step 1 ==0.1秒"""
        self.count = 0
        self.step = step * 0.1
        self.detector_dict = {}  # name,detector
        self.detect_result_dict = {}  # name,result
        self.names = list(self.detector_dict.keys())
        self.current_name = None  # 标记当前检测器
        self.start_time = time.time()
        self.log = Logger(__class__.__name__)

    def add_detector(self, detector):
        self.detector_dict[detector.name] = detector
        self.detect_result_dict[detector.name] = None
        self.count = len(self.detector_dict)
        self.names = list(self.detector_dict.keys())

    def _get_index(self):
        if self.count == 0:
            return -1
        return int((time.time() - self.start_time) / self.step % self.count)

    def _get_detector(self):
        detector = None
        idx = self._get_index()
        if idx == -1:
            return detector
        n = self.names[idx]
        if self.current_name == n:
            pass
        else:
            detector = self.detector_dict[n]
            self.current_name = n
        return detector

    def get_current_detector_name(self):
        if self._get_index() == -1:
            return None
        return self.names[self._get_index()]

    def detect(self, img, identity=None):
        detector = self._get_detector()
        if detector is not None:
            result = detector.detect(img, identity)
            if result is not None and len(result) > 0:
                # self.log.info(detector.name,"检测到",result)
                self.detect_result_dict[self.current_name] = result
            # else:
            # self.log.info(detector.name, "未检测到",)

    def get_result_cls_name(self, detector_name):
        if detector_name not in self.detect_result_dict:
            return None, None
        result = self.detect_result_dict[detector_name]
        detector = self.detector_dict[detector_name]
        txt = detector.get_name_from_result(result)
        cls = detector.get_cls_from_result(result)
        return cls, txt

    def get_results(self):
        ed = {}
        for n in self.names:
            ed[n] = self.detect_result_dict[n]
        return ed
